<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="visible"
      width="600px"
      append-to-body
      :before-close="close"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="入住信息" prop="houseInfo">
          <el-row>
            <el-col :span="14">
              <el-input
                v-model="form.houseInfo"
                placeholder="请输入名称"
                style="width: 240px"
                readonly
              />
            </el-col>
            <el-col :span="10">
              <el-button type="primary" @click="selectHouse">选择</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="费用周期" required>
          <!--          <el-date-picker-->
          <!--            v-model="form.billDate"-->
          <!--            type="daterange"-->
          <!--            range-separator="至"-->
          <!--            start-placeholder="开始日期"-->
          <!--            end-placeholder="结束日期"-->
          <!--            style="width: 240px"-->
          <!--            value-format="yyyy-MM-dd HH:mm:ss"-->
          <!--            @change="billDateChange"-->
          <!--          />-->
          <el-row>
            <el-col :span="11">
              <el-form-item prop="billStartTime">
                <el-date-picker
                  v-model="form.billStartTime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="开始日期"
                  type="date"
                  style="width: 100%"
                  :picker-options="billStartTimeOptions"
                />
              </el-form-item>
            </el-col>
            <el-col :span="2" style="text-align: center">至</el-col>
            <el-col :span="11">
              <el-form-item prop="billStartTime">
                <el-date-picker
                  v-model="form.billEndTime"
                  type="date"
                  placeholder="结束日期"
                  style="width: 100%"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :picker-options="billEndTimeOptions"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="最晚付款日期" prop="latestPayTime">
          <el-date-picker
            v-model="form.latestPayTime"
            type="date"
            placeholder="请选择最晚付款日期"
            style="width: 240px"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="lastPayTimeOptions"
          />
        </el-form-item>
        <el-form-item label="账单生成日期" prop="billCreateTime">

          <el-date-picker
            v-model="form.billCreateTime"
            type="date"
            placeholder="请选择账单生成日期"
            style="width: 240px"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="billCreateTimeOptions"
          />
        </el-form-item>
        <el-form-item label="违约金" prop="penaltyStates">
          <el-radio-group v-model="form.penaltyStates">
            <el-radio label="1">不收取</el-radio>
            <el-radio label="2">收取</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="违约金比例" prop="penaltyScale" v-if="form.penaltyStates == 2">
          <el-input v-model="form.penaltyScale" placeholder="请输入违约金比例" v-input.float="1" style="width: 240px">
            <template slot="append">%</template>
          </el-input>
        </el-form-item>

        <el-form-item prop="houseBillItemMerges" label-width="0">
          <el-button type="primary" size="mini" @click="addRow">新增费用项</el-button>
          费用总计: {{ totalPrice }}
          <el-table
            :data="form.houseBillItemMerges"
            style="width: 100%"
          >
            <el-table-column label="费用名称" prop="itemName">
              <template slot-scope="scope">
                <el-select v-model="scope.row.itemName" placeholder="请选择" filterable>
                  <el-option :label="item.label" :value="item.label" v-for="item in billItemList" :key="item.value"
                  ></el-option>
                </el-select>

              </template>
            </el-table-column>
            <el-table-column label="金额（元）" prop="itemPrice">
              <template slot-scope="scope">
                <!--                <el-input-number v-model="scope.row.itemPrice" :min="0" :step="0.01" :precision="2" style="width: 100%"></el-input-number>-->
                <el-input v-model="scope.row.itemPrice" placeholder="请输入金额" v-input.float="2"
                          @change="(e)=>scope.row.itemPrice = Number(e)"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="deleteRow(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </div>
    </el-dialog>
    <SelectHouse @success="selectHouseCb" v-model="selectHouseVisible"></SelectHouse>
  </div>
</template>

<script>
import { addBillItem, listBillItem, updateBillItem } from '@/api/bill/item'
import { debounce } from '@/utils'
import SelectHouse from './select-house.vue'
import { createHouseBill } from '@/api/bill/houseBill'
import { compareDate } from '@/utils/common/moment'

export default {
  props: {
    value: {
      type: Boolean,
      default: false
    },
    title: {
      default: '新增费用信息'
    },
    data: {
      default: () => ({})
    }
  },
  components: {
    SelectHouse
  },
  dicts: [],
  data() {
    return {
      // 表单参数
      form: {
        houseInfo: '',//房屋名称
        orderId: '',//关联订单id
        houseId: '',//房屋id
        latestPayTime: '',//最晚付款日期
        penaltyStates: '1',//违约金生成状态: 1不收取 2收取
        penaltyScale: '',//违约金比例
        billCreateTime: '',//账单生成时间
        billStartTime: '',//账单开始时间
        billEndTime: '',//账单结束时间
        houseBillItemMerges: []
      },
      houseName: '',
      // 选择房屋弹窗
      selectHouseVisible: false,
      // 费用列表
      billItemList: [],
      // 账单开始日期选项
      billStartTimeOptions: {
        disabledDate:(time)=> {
          return this.form.billEndTime && compareDate(time, this.form.billEndTime, '>')
        }
      },

      // 账单结束日期选项
      billEndTimeOptions: {
        disabledDate:(time)=> {
          return this.form.billStartTime && compareDate(time, this.form.billStartTime, '<')
        }
      },
      // 最晚付款日期选项
      lastPayTimeOptions: {
        disabledDate(time) {
          const today = new Date()
          today.setHours(0, 0, 0, 0)
          return time.getTime() < today.getTime()
        }
      },
      // 账单生成日期选项
      billCreateTimeOptions: {
        disabledDate(time) {
          const today = new Date()
          today.setHours(0, 0, 0, 0)
          return time.getTime() < today.getTime()
        }
      },
      // 表单校验
      rules: {
        houseInfo: [
          { required: true, message: '请选择房屋信息', trigger: 'blur' }
        ],
        billDate: [
          { required: true, message: '请选择费用周期', trigger: 'blur' }
        ],
        billStartTime: [
          { required: true, message: '请选择开始日期', trigger: 'blur' }
        ],
        billEndTime: [
          { required: true, message: '请选择结束日期', trigger: 'blur' }
        ],
        latestPayTime: [
          { required: true, message: '请选择最晚付款日期', trigger: 'blur' }
        ],
        billCreateTime: [
          { required: true, message: '请选择账单生成日期', trigger: 'blur' }
        ],
        penaltyStates: [
          { required: true, message: '请选择违约金生成状态', trigger: 'blur' }
        ],
        penaltyScale: [
          { required: true, message: '请输入违约金比例', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value && value <= 0) {
                callback(new Error('违约金比例需大于0'))
              } else if (value > 100) {
                callback(new Error('违约金比例需小于100'))
              } else {
                callback()
              }
            }
          }
        ],
        houseBillItemMerges: [
          { type: 'array', required: true, message: '请至少添加一项费用', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    visible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val) // 此处监测showMask目的为关闭弹窗时，重新更换value值，注意emit的事件一定要为input。
      }
    },
    // 费用总计
    totalPrice() {
      let total = 0
      total = this.form.houseBillItemMerges.reduce((acc, cur) => Number(acc) + Number(cur.itemPrice), 0)
      return total.toFixed(2)
    }
  },
  watch: {
    value: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.init()
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    init() {
      this.reset()
      this.getBillItemList()
    },
    //重置表单
    reset() {
      this.form = {
        houseInfo: '',//房屋名称
        orderId: '',//关联订单id
        houseId: '',//房屋id
        latestPayTime: '',//最晚付款日期
        penaltyStates: '1',//违约金生成状态: 1不收取 2收取
        penaltyScale: '',//违约金比例
        billCreateTime: '',//账单生成时间
        billStartTime: '',//账单开始时间
        billEndTime: '',//账单结束时间
        houseBillItemMerges: [
          // {
          //   itemName: '',
          //   itemPrice: null
          // }
        ]
      }
      this.resetForm('form')
      if (this.data.itemId) {
        this.form = this.data
      }
    },
    // 选择房屋
    selectHouse() {
      this.selectHouseVisible = true
    },
    selectHouseCb(data) {
      this.form.houseId = data.houseId
      this.form.orderId = data.orderId
      this.form.houseInfo = data.reserveUser + '/' + data.premisesAddress
    },
    // 时间范围回调
    billDateChange(val) {
      this.form.billStartTime = val[0]
      this.form.billEndTime = val[1]
    },
    //获取费用列表
    getBillItemList() {
      listBillItem().then(response => {
        this.billItemList = response.rows.map(item => {
          return {
            label: item.name,
            value: item.itemId
          }
        })
      })
    },
    //新增费用项
    addRow() {
      this.form.houseBillItemMerges.push({
        itemName: '',
        itemPrice: null
      })
    },
    //删除费用项
    deleteRow(index) {
      this.form.houseBillItemMerges.splice(index, 1)
    },

    /** 提交按钮 */
    submitForm: debounce(function() {
      this.$refs['form'].validate((valid) => {
        // 账单生成日期不能晚于最晚付款日期
        if (this.$moment(this.form.billCreateTime).isAfter(this.form.latestPayTime)) {
          this.$message.error('账单生成日期不能晚于最晚付款日期')
          return
        }
        // 校验费用名称和金额
        for (let i = 0; i < this.form.houseBillItemMerges.length; i++) {
          if (this.form.houseBillItemMerges[i].itemName === '') {
            this.$message.error('请选择费用名称')
            return
          }
          if (!this.form.houseBillItemMerges[i].itemPrice) {
            this.$message.error('请输入费用金额')
            return
          }
          if (this.form.houseBillItemMerges[i].itemPrice && this.form.houseBillItemMerges[i].itemPrice <= 0) {
            this.$message.error('费用金额需大于0')
            return
          }
        }
        if (valid) {
          createHouseBill(this.form).then((response) => {
            this.$modal.msgSuccess(response.msg)
            this.$emit('success')
          })
          this.close()
        }
      })
    }, 300, true),
    close() {
      this.reset()
      this.visible = false
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  max-height: 80vh !important;
  overflow-y: auto;
}

</style>
